<template>
  <view class="submit-container">
    <!-- 收货地址 -->
    <view class="address-section" @click="handleSelectAddress">
      <template v-if="selectedAddress">
        <view class="address-info">
          <view class="user-info">
            <text class="name">{{ selectedAddress.receiverName }}</text>
            <text class="phone">{{ selectedAddress.receiverPhone }}</text>
          </view>
          <view class="address">
            {{ formatAddress(selectedAddress) }}
          </view>
        </view>
      </template>
      <view v-else class="no-address">
        <text>请选择收货地址</text>
        <uni-icons type="right" size="16" color="#999"></uni-icons>
      </view>
    </view>

    <!-- 商品列表 -->
    <view class="goods-section">
      <view 
        class="merchant-group"
        v-for="merchant in orderInfo.merchants"
        :key="merchant.merchantId"
      >
        <!-- 商家信息 -->
        <view class="merchant-info">
          <image class="merchant-logo" :src="merchant.logo" mode="aspectFill"></image>
          <text class="merchant-name">{{ merchant.name }}</text>
        </view>

        <!-- 商品列表 -->
        <view class="goods-list">
          <view 
            class="goods-item"
            v-for="item in merchant.items"
            :key="item.id"
          >
            <image class="goods-image" :src="item.image" mode="aspectFill"></image>
            <view class="goods-info">
              <text class="goods-name">{{ item.name }}</text>
              <text class="goods-spec" v-if="item.specInfo">{{ item.specInfo }}</text>
              <view class="goods-price-wrap">
                <text class="goods-price">¥{{ item.price }}</text>
                <text class="goods-quantity">x{{ item.quantity }}</text>
              </view>
            </view>
          </view>
        </view>

        <!-- 商家小计 -->
        <view class="merchant-total">
          <text>共{{ merchant.totalQuantity }}件商品</text>
          <text>小计：¥{{ merchant.totalAmount }}</text>
        </view>
      </view>
    </view>

    <!-- 订单信息 -->
    <view class="order-info">
      <view class="info-item">
        <text class="label">支付方式</text>
        <text class="value">在线支付</text>
      </view>
      <view class="info-item">
        <text class="label">优惠券</text>
        <view class="value coupon" @click="handleSelectCoupon">
          <text>{{ selectedCoupon ? `省${selectedCoupon.amount}元` : '暂无可用' }}</text>
          <uni-icons type="right" size="16" color="#999"></uni-icons>
        </view>
      </view>
      <view class="info-item">
        <text class="label">订单备注</text>
        <input 
          class="value remark"
          v-model="remark"
          placeholder="选填，填写订单备注"
          placeholder-class="placeholder"
        />
      </view>
    </view>

    <!-- 底部结算栏 -->
    <view class="bottom-bar">
      <view class="price-info">
        <text>实付款：</text>
        <text class="total-price">¥{{ orderInfo.totalAmount }}</text>
      </view>
      <button 
        class="submit-btn" 
        :disabled="!canSubmit"
        :loading="submitting"
        @click="handleSubmit"
      >
        提交订单
      </button>
    </view>
  </view>
</template>

<script>
import payment from '../../../config/api/modules/payment'

export default {
  data() {
    return {
      orderInfo: {
        totalAmount: 0,
        totalQuantity: 0,
        merchants: []
      },
      selectedAddress: null,
      selectedCoupon: null,
      remark: '',
      submitting: false
    }
  },

  computed: {
    canSubmit() {
      return this.selectedAddress && this.orderInfo.totalAmount > 0
    }
  },

  onLoad(options) {
    // 解析预览数据
    const preview = uni.getStorageSync('orderPreview')
    if (preview) {
      this.orderInfo = preview
      uni.removeStorageSync('orderPreview')
    }
    
    // 加载默认地址
    this.loadDefaultAddress()
  },

  methods: {
    // 加载默认地址
    async loadDefaultAddress() {
      try {
        const { data } = await this.$api.user.address.getDefault()
        if (data) {
          this.selectedAddress = data
        }
      } catch (error) {
        console.error('加载默认地址失败:', error)
      }
    },

    // 格式化地址
    formatAddress(address) {
      return `${address.province}${address.city}${address.district}${address.detailAddress}`
    },

    // 选择地址
    handleSelectAddress() {
      uni.navigateTo({
        url: '/pages/user/address/index?from=order'
      })
    },

    // 更新选择的地址
    updateAddress(address) {
      this.selectedAddress = address
    },

    // 选择优惠券
    handleSelectCoupon() {
      // TODO: 实现优惠券选择
      uni.showToast({
        title: '暂无可用优惠券',
        icon: 'none'
      })
    },

    // 提交订单
    async handleSubmit() {
      if (!this.canSubmit) return
      if (this.submitting) return

      try {
        this.submitting = true

        // 构建订单数据
        const orderData = {
          addressId: this.selectedAddress.id,
          couponId: this.selectedCoupon?.id,
          remark: this.remark,
          useCart: true, // 从购物车提交订单
          cartItemIds: Array.from(this.orderInfo.cartItemIds || []) // 确保是普通数组
        }

        console.log('提交订单数据：', orderData)

        // 提交订单
        const res = await this.$api.orders.submit(orderData)
        
        // 确保返回数据正确
        if (res.code !== 200 || !res.data || !Array.isArray(res.data)) {
          throw new Error(res.message || '订单创建失败')
        }

        // 存储支付信息
        const paymentInfo = {
          orderIds: res.data, // 直接使用返回的订单ID数组
          totalAmount: this.orderInfo.totalAmount
        }
        
        // 打印日志，方便调试
        console.log('订单提交响应：', res)
        console.log('支付信息：', paymentInfo)
        
        // 存储到本地
        uni.setStorageSync('paymentInfo', paymentInfo)

        // 跳转到支付页面
        uni.redirectTo({
          url: '/pages/order/pay/index'
        })
      } catch (error) {
        console.error('提交订单失败：', error)
        uni.showToast({
          title: error.message || '提交订单失败',
          icon: 'none'
        })
      } finally {
        this.submitting = false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.submit-container {
  min-height: 100vh;
  background-color: #f8f8f8;
  padding-bottom: 120rpx;
}

.address-section {
  background-color: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
  
  .address-info {
    .user-info {
      margin-bottom: 10rpx;
      
      .name {
        font-size: 32rpx;
        color: #333;
        font-weight: 500;
        margin-right: 20rpx;
      }
      
      .phone {
        font-size: 28rpx;
        color: #666;
      }
    }
    
    .address {
      font-size: 28rpx;
      color: #666;
      line-height: 1.4;
    }
  }
  
  .no-address {
    display: flex;
    align-items: center;
    justify-content: space-between;
    
    text {
      font-size: 28rpx;
      color: #999;
    }
  }
}

.goods-section {
  background-color: #fff;
  margin-bottom: 20rpx;
  
  .merchant-group {
    .merchant-info {
      display: flex;
      align-items: center;
      padding: 20rpx 30rpx;
      border-bottom: 1rpx solid #f5f5f5;
      
      .merchant-logo {
        width: 48rpx;
        height: 48rpx;
        border-radius: 8rpx;
        margin-right: 16rpx;
      }
      
      .merchant-name {
        font-size: 28rpx;
        color: #333;
        font-weight: 500;
      }
    }
    
    .goods-list {
      .goods-item {
        display: flex;
        padding: 20rpx 30rpx;
        
        .goods-image {
          width: 160rpx;
          height: 160rpx;
          border-radius: 8rpx;
        }
        
        .goods-info {
          flex: 1;
          margin-left: 20rpx;
          display: flex;
          flex-direction: column;
          
          .goods-name {
            font-size: 28rpx;
            color: #333;
            line-height: 1.4;
            margin-bottom: 8rpx;
          }
          
          .goods-spec {
            font-size: 24rpx;
            color: #999;
            margin-bottom: 8rpx;
          }
          
          .goods-price-wrap {
            display: flex;
            justify-content: space-between;
            align-items: center;
            
            .goods-price {
              font-size: 32rpx;
              color: #ff5500;
              font-weight: bold;
            }
            
            .goods-quantity {
              font-size: 24rpx;
              color: #999;
            }
          }
        }
      }
    }
    
    .merchant-total {
      display: flex;
      justify-content: flex-end;
      align-items: center;
      padding: 20rpx 30rpx;
      border-top: 1rpx solid #f5f5f5;
      
      text {
        font-size: 24rpx;
        color: #666;
        margin-left: 20rpx;
        
        &:last-child {
          color: #333;
          font-weight: 500;
        }
      }
    }
  }
}

.order-info {
  background-color: #fff;
  padding: 0 30rpx;
  
  .info-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 88rpx;
    border-bottom: 1rpx solid #f5f5f5;
    
    &:last-child {
      border-bottom: none;
    }
    
    .label {
      font-size: 28rpx;
      color: #333;
    }
    
    .value {
      font-size: 28rpx;
      color: #666;
      
      &.coupon {
        display: flex;
        align-items: center;
        
        text {
          margin-right: 10rpx;
        }
      }
      
      &.remark {
        text-align: right;
        width: 400rpx;
      }
    }
  }
}

.bottom-bar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  height: 100rpx;
  background-color: #fff;
  display: flex;
  align-items: center;
  padding: 0 30rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
  
  .price-info {
    flex: 1;
    
    text {
      font-size: 28rpx;
      color: #333;
      
      &.total-price {
        font-size: 36rpx;
        color: #ff5500;
        font-weight: bold;
      }
    }
  }
  
  .submit-btn {
    width: 240rpx;
    height: 80rpx;
    line-height: 80rpx;
    text-align: center;
    background-color: #ff5500;
    color: #fff;
    font-size: 32rpx;
    border-radius: 40rpx;
    
    &[disabled] {
      background-color: #ddd;
    }
    
    &[loading] {
      opacity: 0.8;
    }
  }
}

.placeholder {
  color: #999;
}
</style> 